package org.swim.web.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.WordUtils;
import org.swim.remote.entities.ICollaboration;
import org.swim.remote.entities.IFriendship;
import org.swim.remote.entities.IFriendship.Status;
import org.swim.remote.entities.IUser;

public class SwimUtils {
	public static Boolean isLogged(HttpServletRequest request) {
		final String TOKEN = "token";
		String token = (String) request.getSession().getAttribute(TOKEN);
		if (token == null)
			return false;
		else
			return true;

	}

	public static String capitalizeFirstChar(String line) {
		return Character.toUpperCase(line.charAt(0)) + line.substring(1);
	}

	public static String capitalizaName(String name) {
		return WordUtils.capitalize(WordUtils.capitalize(name),
				new char[] { '\'' });
	}

	public static String getName(IUser user) {
		if (user == null || user.getFullName().equals("")
				|| user.getFullName().equals("NO NAME AND NO SURNAME")) {
			return "Someone";
		} else {
			return SwimUtils.capitalizaName(user.getFullName().toLowerCase());
		}
	}

	public static IFriendship getFriendship(IUser firstUser, IUser secondUser) {

		if (firstUser == null || secondUser == null)
			return null;

		List<IFriendship> friendship = new ArrayList<IFriendship>(
				firstUser.getFriendshipsForReceiverIdSet());

		for (IFriendship iFriendship : friendship) {
			if (iFriendship.getUserBySenderId().equals(secondUser))
				return iFriendship;
		}

		friendship = new ArrayList<IFriendship>(
				firstUser.getFriendshipsForSenderIdSet());

		for (IFriendship iFriendship : friendship) {
			if (iFriendship.getUserByReceiverId().equals(secondUser))
				return iFriendship;
		}

		return null;
	}

	public static boolean areFriends(IUser firstUser, IUser secondUser) {
		IFriendship friendship = getFriendship(firstUser, secondUser);

		if (friendship != null && friendship.getStatus() == Status.CONFIRMED)
			return true;

		return false;
	}

	public static String formatDate(Date date, String format) {
		DateFormat formatter = new SimpleDateFormat(format);
		String s = formatter.format(date);
		return s;
	}

	public static IUser getCollaborator(ICollaboration collaboration, IUser me) {
		if (collaboration.getIUserBySenderId() != null
				&& collaboration.getIUserBySenderId().equals(me))
			return collaboration.getUserByReceiverId();
		else if (collaboration.getUserByReceiverId() != null
				&& collaboration.getUserByReceiverId().equals(me))
			return collaboration.getIUserBySenderId();
		else
			return null;
	}
}
